import React, { useEffect } from 'react';
import { useSearchParams } from 'react-router-dom';
import { ResultCard } from '../components/ResultCard';
import { SearchBox } from '../components/SearchBox';
import { Database, Loader2 } from 'lucide-react';
import { useSearch } from '../hooks/useSearch';

export function Search() {
  const [searchParams, setSearchParams] = useSearchParams();
  const query = searchParams.get('q') || '';
  const { results, loading, loadMore } = useSearch(query);

  const handleSearch = (newQuery: string) => {
    setSearchParams({ q: newQuery });
  };

  useEffect(() => {
    const handleScroll = () => {
      if (
        window.innerHeight + document.documentElement.scrollTop
        === document.documentElement.offsetHeight
      ) {
        loadMore();
      }
    };

    window.addEventListener('scroll', handleScroll);
    return () => window.removeEventListener('scroll', handleScroll);
  }, [loadMore]);

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="bg-white shadow-sm">
        <div className="container mx-auto px-4 py-4">
          <div className="flex items-center gap-3 mb-4">
            <a href="/" className="flex items-center gap-2">
              <Database className="w-8 h-8 text-blue-500" />
              <span className="text-xl font-bold text-gray-900">数据图表查询</span>
            </a>
          </div>
          <SearchBox onSearch={handleSearch} />
        </div>
      </div>

      <div className="container mx-auto px-4 py-8">
        <div className="grid gap-6">
          {results.map(result => (
            <ResultCard key={result.id} data={result} />
          ))}
        </div>
        
        {loading && (
          <div className="flex justify-center py-8">
            <Loader2 className="w-8 h-8 animate-spin text-blue-500" />
          </div>
        )}
      </div>
    </div>
  );
}
